package org.rabbitmq.four;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import org.rabbitmq.utils.RabbitMqUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

public class ConfirmMessage {
    //批量发消息个数
    public static final int MESSAGE_COUNT = 1000;

    public static void main(String[] args) throws Exception {
        //单个确认
//        publishMessageIndividually();
        //批量
//        publishMessageBath();
        //异步
        publishMessageAsync();
    }

    //单个确认
    public static void publishMessageIndividually() throws Exception {
        Channel channel = RabbitMqUtils.getChannel();

        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();
        //开始时间
        long begin = System.currentTimeMillis();

        for (int i = 0; i<MESSAGE_COUNT;i++){
            String message = "消息"+i;
            channel.basicPublish("",queueName,null,message.getBytes());
            boolean flag = channel.waitForConfirms();
            if (flag){
                System.out.println("消息发送成功");
            }
        }
//        结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"个消息，需要："+(end-begin));
    }

    //批量发布
    public static void publishMessageBath() throws Exception {
        Channel channel = RabbitMqUtils.getChannel();

        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();
        //开始时间
        long begin = System.currentTimeMillis();

        //批量确定规范
        int batchSize = 100;
        for (int i = 0; i<MESSAGE_COUNT;i++){
            String message = "消息"+i;
            channel.basicPublish("",queueName,null,message.getBytes());
            if (i+1%batchSize ==0){
                channel.waitForConfirms();
                System.out.println("消息发送成功:"+message);
            }
        }
//        结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"个消息，需要："+(end-begin));
    }

    //异步发布
    public static void publishMessageAsync() throws Exception {
        Channel channel = RabbitMqUtils.getChannel();

        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();
        /**
         * 线程安全有序的一个哈希表，适用于高并发的情况下
         * 1.轻松的将序号与消息进行关联
         * 2.轻松的批量删除的条目
         * 3.支持高并发（多线程）
         */
        ConcurrentSkipListMap<Long,String> outstandingConfirms = new ConcurrentSkipListMap<>();

        //开始时间
        long begin = System.currentTimeMillis();
        //消息确认成功回调方法
        ConfirmCallback confirmCallback = (deliveryTag,multiple) ->{
            if (multiple){
                ConcurrentNavigableMap<Long, String> confirmed = outstandingConfirms.headMap(deliveryTag);
                confirmed.clear();
            }else {
                outstandingConfirms.remove(deliveryTag);
            }
            //删除已经确认的消息
            System.out.println("删除确认的消息"+deliveryTag);
        };
        //消息确认失败回调
        /**
         * 1.消息的标识标记
         * 2.是否未批量确认
         */
        ConfirmCallback nackCallback = (deliveryTag,multiple) ->{
            //打印未确认消息
            System.out.println("未确认的消息："+deliveryTag);
        };


        //消息监听器，监听哪些消息成功了，哪些消息失败了
        channel.addConfirmListener(confirmCallback,confirmCallback);
        for (int i = 0; i<MESSAGE_COUNT;i++){
            String message = "消息"+i;
            channel.basicPublish("",queueName,null,message.getBytes());
            outstandingConfirms.put(channel.getNextPublishSeqNo(),message);
            //1.记录所以要发送消息
        }
//        结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"个异步消息，需要："+(end-begin));
    }
}
